package com.hyzh.latte.sandtable.service;

import com.hyzh.latte.sandtable.mapper.GeoQueryMapper;
import com.hyzh.latte.sandtable.mapper.TableMapper;
import com.hyzh.latte.sandtable.mapper.VectorMapper;
import com.hyzh.latte.sandtable.pojo.Graph.PointNode;
import com.hyzh.latte.sandtable.pojo.Vector_Line_2D;
import com.hyzh.latte.sandtable.pojo.Vector_Point_2D;
import com.hyzh.latte.sandtable.utils.VectorUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Service
@AllArgsConstructor
public class VectorService {
    private final VectorMapper vectorMapper;
    private final TableMapper tableMapper;
    private final GraphService graphService;
    private final GeoQueryMapper geoQueryMapper;

    public void updateRoad(ArrayList<Vector_Line_2D> lines, String area) {
        String lineTableName = area + "_line";
        String nodeTableName = area + "_node";
        String graphTableName = area + "_graph";
        tableMapper.createLineTable(lineTableName);
        tableMapper.createNodeTable(nodeTableName);
        lines.forEach((element) -> {
            vectorMapper.insertRoad(element, lineTableName);
        });
        ArrayList<Vector_Point_2D> nodes = VectorUtils.generateNodeFromLine(lines);
        nodes.forEach((element) -> {
            vectorMapper.insertNode(element, nodeTableName);
        });

        for (int i = 0; i < lines.size(); i++) {
            Vector_Line_2D element = lines.get(i);
            Integer index = i + 1;
            double distance = geoQueryMapper.selectLengthByLineIndex(index, lineTableName);
            Vector_Point_2D point0 = new Vector_Point_2D(element.getStartX(), element.getStartY());
            Integer indexOfPoint0 = VectorUtils.findIndexFromNodeList(point0, nodes);
            PointNode pointNode0 = new PointNode(point0, indexOfPoint0);
            Vector_Point_2D point1 = new Vector_Point_2D(element.getEndX(), element.getEndY());
            Integer indexOfPoint1 = VectorUtils.findIndexFromNodeList(point1, nodes);
            PointNode pointNode1 = new PointNode(point1, indexOfPoint1);
            graphService.createRelationshipBetweenPoints(pointNode0, pointNode1, distance, graphTableName);
        }

    }
}
